package com.zsc.edu.testbroadcastsender;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    // 本地广播管理者，用于发送和注册本地广播
    LocalBroadcastManager mLocalBroadcastManager;
    // 本地广播接收者，用于接收本地广播
    LocalBroadcastReceiver mLocalBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_send_broadcast).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 构造一个intent, 指定发送广播的action
                Intent intent = new Intent("com.zsc.edu.testbroadcastsender.MY_BROADCAST");
                // 发送标准广播
                //sendBroadcast(intent);
                // 发送有序广播
                sendOrderedBroadcast(intent, null);
            }
        });

        // 得到本地广播管理器的实例
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

        // 注册本地广播
        // 利用IntentFilter，指定需要接收的广播的行为
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.zsc.edu.testbroadcastsender.LOCAL_BROADCAST");
        mLocalBroadcastReceiver = new LocalBroadcastReceiver();

        // 使用 本地广播管理器 注册本地广播
        mLocalBroadcastManager.registerReceiver(mLocalBroadcastReceiver, intentFilter);

        findViewById(R.id.btn_send_local_broadcast).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 构造一个intent, 指定发送广播的action
                Intent intent = new Intent("com.zsc.edu.testbroadcastsender.LOCAL_BROADCAST");
                //  使用 本地广播管理器 发送本地广播
                mLocalBroadcastManager.sendBroadcast(intent);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocalBroadcastManager.unregisterReceiver(mLocalBroadcastReceiver);
    }
}